package com.wyl.auth.common.service.impl;

import com.wyl.auth.common.service.FileService;
import com.wyl.auth.config.minio.MinioClientService;
import com.wyl.auth.config.minio.MinioProperty;
import com.wyl.auth.exception.BusinessException;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2024/6/23 10:35
 */
@Service
public class MinioServiceImpl implements FileService {

    @Autowired
    private MinioProperty minioProperty;

    @Override
    public String upload(MultipartFile file)  {
        try{
            MinioClient minioClient = MinioClientService.createMinioClient();
            PutObjectArgs build = PutObjectArgs.builder()
                    .bucket(minioProperty.getBucket()).object(file.getOriginalFilename()).stream(file.getInputStream(), file.getInputStream().available(), -1)
                    .contentType(file.getContentType())
                    .build();
            ObjectWriteResponse objectWriteResponse = minioClient.putObject(build);
            String url = minioProperty.getEndpoint() + "/" + minioProperty.getBucket() + "/" + objectWriteResponse.object();
            return  url;
        }catch (Exception e){
           throw new BusinessException("上传异常");
        }
    }
}